import pandas as pd
from deep_translator import GoogleTranslator
from snownlp import SnowNLP
from snownlp import seg

import time

df = pd.read_csv('B0FKFW63KK评论数据.csv')

# 初始化翻译器
translator = GoogleTranslator(source='auto', target='zh-CN')

# 1. 定义要扩充的新词列表
new_words = ["大容量", "耐热", "透明"]

# 2. 将新词添加到分词器的词典中（词频设为1000，词性设为n）
for word in new_words:
    seg(word)   # seg.dict是SnowNLP的核心词典对象


# 提取正面/负面评论的核心关键词
def get_top_keywords(text_list, top_k=12):
    # 合并所有文本
    combined_text = " ".join(text_list)
    # 提取Top K关键词
    keywords = SnowNLP(combined_text).keywords(limit=top_k)
    return keywords


sentiment_results = []
# 遍历comment列并翻译
for idx, comment in enumerate(df['comment']):
    if str(comment) is None:
        print("数据读取为空或失败")
        continue

    translated = translator.translate(str(comment))

    if len(comment) < 2:
        continue

    sentiment_score = SnowNLP(translated).sentiments
    score = round(sentiment_score, 2)
    # 自定义情感标签（根据业务调整阈值，这里用0.6为正面，0.4为负面）
    if score >= 0.6:
        label = "正面"
    elif score <= 0.4:
        label = "负面"
    else:
        label = "中性"
    print({"评论": translated, "情感得分": score, "标签": label})
    sentiment_results.append({"评论": translated, "情感得分": score, "标签": label})

positive_texts = [res["评论"] for res in sentiment_results if res["标签"] == "正面"]
positive_keywords = get_top_keywords(positive_texts)
print("正面评论核心关键词：", positive_keywords)
